import { ref, onMounted, onUnmounted } from "vue";
import { throttle } from "@/utils/tools";
export function useInfiniteScroll(loadMore, options = {}) {
  const { distance = 100, immediate = true, disabled = false } = options;

  const loading = ref(false);
  const finished = ref(false);
  const error = ref(null);
  const page = immediate ? ref(1) : ref(2);

  const containerRef = ref(null);

  const handleScroll = async () => {
    if (loading.value || finished.value || disabled || !containerRef.value)
      return;
    const { scrollTop, scrollHeight, clientHeight } = containerRef.value;
    if (scrollHeight - scrollTop - clientHeight <= distance) {
      try {
        loading.value = true;
        await loadMore(page.value);
        loading.value = false;
        page.value++;
      } catch (err) {
        error.value = err;
        console.error("加载更多数据失败:", err);
      } finally {
        loading.value = false;
      }
    } else {
      if (page.value == 1) {
        loading.value = true;
        await loadMore(page.value);
        loading.value = false;
        page.value++;
      }
    }
  };

  const reset = async () => {
    page.value = 1;
    finished.value = false;
    error.value = null;
    loading.value = true;
    containerRef.value.scrollTop = 0;
    // containerRef.value.style.overflow = "hidden";
    containerRef.value?.removeEventListener(
      "scroll",
      throttle(handleScroll, 500)
    );
    await loadMore(page.value);
    page.value++;
    loading.value = false;
    containerRef.value?.addEventListener("scroll", throttle(handleScroll, 500));
    // containerRef.value.style.overflow = "";
  };

  const finish = () => {
    finished.value = true;
  };

  onMounted(() => {
    if (immediate && containerRef.value) {
      handleScroll();
    }
    containerRef.value?.addEventListener("scroll", throttle(handleScroll, 500));
    console.log("Infinite scroll mounted");
  });

  onUnmounted(() => {
    containerRef.value?.removeEventListener(
      "scroll",
      throttle(handleScroll, 500)
    );
    console.log("Infinite scroll unmounted");
  });

  return {
    loading,
    finished,
    error,
    page,
    reset,
    finish,
    containerRef,
  };
}
